<template>
  <div class="bed-distribution-chart">
    <div class="chart-header">
      <h3>床铺分布情况</h3>
    </div>
    <div class="chart-container">
      <div class="bar-chart-wrapper" ref="barChartContainer"></div>
    </div>
  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'BedDistributionChart',
  data() {
    return {
      chart: null,
      mockData: []
    }
  },
  mounted() {
    this.generateMockData()
    this.initChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.destroy()
    }
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  methods: {
    generateMockData() {
      // 生成11个监区的床铺数据
      this.mockData = []

      for (let i = 1; i <= 11; i++) {
        // 每个监区的基础床位数在80-120之间随机
        const baseBeds = 80 + Math.floor(Math.random() * 40)
        // 已使用床位数为0-100%的随机比例
        const usageRatio = Math.random()
        const usedBeds = Math.floor(baseBeds * usageRatio)
        const availableBeds = baseBeds - usedBeds

        this.mockData.push({
          area: `第${i}监区`,
          used: usedBeds,
          available: availableBeds,
          total: baseBeds,
          usageRate: Number((usageRatio * 100).toFixed(1))
        })
      }
    },

    initChart() {
      this.$nextTick(() => {
        if (this.chart) {
          this.chart.destroy()
        }

        const container = this.$refs.barChartContainer
        if (!container) return

        this.chart = new Chart({
          container,
          autoFit: true,
          height: 300
        })

        // 准备堆叠柱状图数据
        const stackedData = []
        this.mockData.forEach(item => {
          stackedData.push({
            area: item.area,
            type: '已使用',
            count: item.used,
            color: '#ff6b6b'
          })
          stackedData.push({
            area: item.area,
            type: '可用',
            count: item.available,
            color: '#00ffff'
          })
        })

        this.chart.data(stackedData)

        this.chart
          .interval()
          .transform({ type: 'stackY' })
          .encode('x', 'area')
          .encode('y', 'count')
          .encode('color', 'type')
          .style('fillOpacity', 0.8)
          .tooltip((data) => {
            const item = this.mockData.find(d => d.area === data.area)
            if (data.type === '已使用') {
              return {
                name: `${data.area} - 已使用`,
                value: `${data.count}床 (${item.usageRate}%)`
              }
            } else {
              return {
                name: `${data.area} - 可用`,
                value: `${data.count}床`
              }
            }
          })
          .legend({
            position: 'top-right',
            color: {
              itemLabelFill: '#fff'
            }
          })
          .axis('x', {
            title: false,
            labelFill: '#fff',
            labelFontSize: 12
          })
          .axis('y', {
            title: false,
            labelFill: '#fff',
            labelFontSize: 12
          })
          .animate('enter', { type: 'growInY', duration: 1000 })

        this.chart.theme({
          background: 'transparent',
          view: {
            viewFill: 'transparent'
          }
        })

        this.chart.render()
      })
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateChartData()
      }, 15000) // 每15秒更新一次
    },

    updateChartData() {
      // 轻微更新数据以模拟变化
      this.mockData.forEach(item => {
        // 随机调整使用率
        const change = (Math.random() - 0.5) * 0.2
        let newUsageRate = item.usageRate / 100 + change
        newUsageRate = Math.max(0, Math.min(1, newUsageRate))

        const newUsed = Math.floor(item.total * newUsageRate)
        item.used = newUsed
        item.available = item.total - newUsed
        item.usageRate = Number((newUsageRate * 100).toFixed(1))
      })

      if (this.chart) {
        // 重新生成堆叠数据
        const stackedData = []
        this.mockData.forEach(item => {
          stackedData.push({
            area: item.area,
            type: '已使用',
            count: item.used,
            color: '#ff6b6b'
          })
          stackedData.push({
            area: item.area,
            type: '可用',
            count: item.available,
            color: '#00ffff'
          })
        })

        this.chart.changeData(stackedData)
      }
    }
  }
}
</script>

<style scoped>
.bed-distribution-chart {
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  padding: 10px;
  padding-top: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
  margin-left: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(45deg,
    rgba(0, 120, 160, 0.9) 0%,
    rgba(0, 100, 140, 0.8) 50%,
    rgba(0, 80, 120, 0.7) 100%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 10px rgba(0, 100, 150, 0.4);
}

.chart-container {
  flex: 1;
  display: flex;
  align-items: center;
}

.bar-chart-wrapper {
  flex: 1;
  min-height: 300px;
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bed-distribution-chart {
    padding: 10px;
  }

  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .chart-header h3 {
    font-size: 14px;
  }

  .bar-chart-wrapper {
    min-height: 250px;
  }
}
</style>
